import { Message } from 'element-ui'
import request from "@/utils/request";

function showError(message) {
  Message({
    message,
    type: 'error',
    duration: 3 * 1000
  })
}

/**
 * 处理根节点非重复数据
 * @param {Object} formConf 表单设计数据
 * @param {Object} data 表单提交数据
 * @param {String} project 项目id
 * @param {String} id 提交数据的id
 * @param {String} title 表单名称
 * @param {Function} success 提交数据的函数
 * @returns 
 */
export async function handleNoRepeatData(headers, formConf, data, project, id, title, success) {
  if (formConf.noRepeatFields && formConf.noRepeatFields.length) {
    let uniq_keys = [];
    for (const key in data) {
      if (Object.hasOwnProperty.call(data, key)) {
        if (formConf.noRepeatFields.includes(key)) {
          let __config__ = formConf.fields.find(
            (item) => item.__vModel__ === key
          ).__config__;
          if (
            __config__.tag !== "jl-extend-number" ||
            (__config__.tag === "jl-extend-number" &&
              data[key] != "UK" &&
              data[key] != "ND" &&
              data[key] != "NA")
          ) {
            uniq_keys.push({
              key,
              label: __config__.label,
              value: data[key],
            });
          }
        }
      }
    }
    for (const uniq_key of uniq_keys) {
      let { key, value, label } = uniq_key;
      let { patient } = await request.post(`/patient-query`, {
        project,
        id,
        [`payload.${key}`]: value,
      }, {
        headers,
      });
      if (patient) {
        showError(`${label}不可与其他${title}重复`)
        return;
      }
    }
    success()
  } else {
    success();
  }
}